package com.ny.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
public class EmailUntil {
    
    @Autowired
    private JavaMailSender mailSender;
    
    // 生成四位随机验证码
    public static String generateVerificationCode() {
        Random random = new Random();
        int code = random.nextInt(9000) + 1000; // 生成1000-9999之间的随机数
        return String.valueOf(code);
    }
    
    // 发送验证码邮件
    public void sendVerificationCode(String toEmail, String verificationCode) {
        // 创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1767293145@qq.com");
        message.setTo(toEmail);
        message.setSubject("智能物联网系统密码重置验证码");
        message.setText("您的验证码是: " + verificationCode + "，有效期5分钟。如非本人操作，请忽略此邮件。");
        
        // 发送邮件
        try {
            mailSender.send(message);
            System.out.println("验证码邮件已发送至: " + toEmail);
        } catch (Exception e) {
            System.err.println("发送邮件失败: " + e.getMessage());
        }
    }
}